package com.coocaa.ops.admin.base.aspect;

import com.coocaa.ops.admin.async.MyAsyncOpsMgrServiceImpl;
import com.coocaa.ops.admin.base.aspect.validator.AspectParamsValidator;
import com.coocaa.ops.admin.base.language.CommonLanguageProperties;
import com.coocaa.ops.admin.base.util.WebUtil;
import com.coocaa.ops.admin.v1.audit.model.ExecutionTaskModel;
import com.coocaa.ops.common.core.base.util.ResourceStatusValidator;
import com.coocaa.ops.common.tool.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Map;

/**
 * @author tangminghong
 * @date 2020-06-18
 */
@Slf4j
@Component
@Aspect
public class AuditAspect {

    @Autowired
    private MyAsyncOpsMgrServiceImpl myAsyncOpsMgrService;
    private static CommonLanguageProperties commonLanguageProperties;

    @Pointcut("@annotation(com.coocaa.ops.admin.base.annotation.AuditOps)")
    public void auditTaskPointcut() {

    }

    /**
     * 审核切面处理
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(returning = "result", pointcut = "auditTaskPointcut()")
    public void auditTask(JoinPoint joinPoint, Object result) {
        if (!(result instanceof Map)) {
            throw new BusinessException(null, "The return value type of auditTask audit method must be Map!");
        }
        Map map = (Map) result;
        String code = (String) map.get("code");
        if (!AspectParamsValidator.isSuccess(code)) {
            //若是审核异常，则不会更新缓存
            return;
        }
        ExecutionTaskModel executionTaskModel = (ExecutionTaskModel) map.get("data");
        Assert.notNull(executionTaskModel, "audit task params " + commonLanguageProperties.getNotNull());
        Integer auditStatus = executionTaskModel.getAuditFlag();
        if (ResourceStatusValidator.isOnline(auditStatus)) {
            //审核通过的
            myAsyncOpsMgrService.handleCommonAsyncOps(executionTaskModel, WebUtil.getUserId());
        }
    }

    @Autowired
    public void setCommonLanguageProperties(CommonLanguageProperties commonLanguageProperties) {
        AuditAspect.commonLanguageProperties = commonLanguageProperties;
    }

    /*************** ===私有方法=== ********************* ===start=== ***************************************/


}
